package com.cloud.picture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.picture.exception.BusinessException;
import com.cloud.picture.mapper.SpaceMapper;
import com.cloud.picture.model.dto.DeleteRequest;
import com.cloud.picture.model.dto.space.SpaceAddRequest;
import com.cloud.picture.model.dto.space.SpaceEditRequest;
import com.cloud.picture.model.dto.space.SpaceQueryRequest;
import com.cloud.picture.model.dto.space.SpaceUpdateRequest;
import com.cloud.picture.model.entity.Space;
import com.cloud.picture.model.entity.User;
import com.cloud.picture.model.enums.ErrorCodeEnum;
import com.cloud.picture.model.enums.SpaceLevelEnum;
import com.cloud.picture.model.vo.SpaceVO;
import com.cloud.picture.model.vo.UserVO;
import com.cloud.picture.service.SpaceService;
import com.cloud.picture.service.UserService;
import com.cloud.picture.utils.ThrowUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
* @author win
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-03-01 10:52:50
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{

    @Resource
    private UserService userService;
    @Autowired
    private TransactionTemplate transactionTemplate;

    Map<Long, Object> lockMap = new ConcurrentHashMap<>();

    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCodeEnum.PARAMS_ERROR);

        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        // 创建
        if (add) {
            ThrowUtils.throwIf(CharSequenceUtil.isBlank(spaceName), ErrorCodeEnum.PARAMS_ERROR, "空间名称为空");
            ThrowUtils.throwIf(spaceLevel == null, ErrorCodeEnum.PARAMS_ERROR, "空间级别为空");
        }
        // 修改
        ThrowUtils.throwIf(spaceLevel != null && spaceLevelEnum == null, ErrorCodeEnum.PARAMS_ERROR,"错误的空间类别");
        ThrowUtils.throwIf(CharSequenceUtil.isNotBlank(spaceName) && spaceName.length() > 30, ErrorCodeEnum.PARAMS_ERROR, "空间名称过长");
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        // 根据空间等级自动填充参数
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVoPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        List<SpaceVO> spaceVOList = spaceList.stream()
                .map(SpaceVO::objToVo)
                .collect(Collectors.toList());
        Set<Long> userIdSet = spaceList.stream()
                .map(Space::getUserId)
                .collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap =
                userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId), "user_id", userId);
        queryWrapper.like(CharSequenceUtil.isNotBlank(spaceName), "space_name", spaceName);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceLevel), "space_level", spaceLevel);
        queryWrapper.orderBy(CharSequenceUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }

    @Override
    public Long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        // 默认值
        if (StrUtil.isBlank(space.getSpaceName())) {
            space.setSpaceName("未命名空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null) {
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        // 填充参数
        fillSpaceBySpaceLevel(space);
        // 校验
        validSpace(space, true);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        // 权限
        if (SpaceLevelEnum.COMMON.getValue() != spaceAddRequest.getSpaceLevel()
                && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH_ERROR, "无权限");
        }
        Object lock = lockMap.computeIfAbsent(userId, k -> new Object());
        synchronized (lock) {
            Long newSpaceId = transactionTemplate.execute(status -> {
                boolean exits = this.lambdaQuery().eq(Space::getUserId, userId).exists();
                ThrowUtils.throwIf(exits, ErrorCodeEnum.OPERATION_ERROR, "用户只能创建一个空间");
                // 插入数据
                boolean save = this.save(space);
                ThrowUtils.throwIf(!save, ErrorCodeEnum.OPERATION_ERROR, "创建空间失败");
                return space.getId();
            });
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }
    }

    @Override
    public Boolean deleteSpace(DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest.getId() <= 0, ErrorCodeEnum.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 2. 判断是否存在
        Space oldSpace = this.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        // 3. 权限认证
        this.checkSpaceAuth(loginUser, oldSpace);
        // 4. 删除
        boolean res = this.removeById(id);
        // @Todo 删除对应空间的文件
        ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
        // 5. 返回结果
        return true;
    }

    @Override
    public Boolean updateSpace(SpaceUpdateRequest spaceUpdateRequest) {
        // 1. 校验
        ThrowUtils.throwIf(spaceUpdateRequest.getId() <= 0, ErrorCodeEnum.PARAMS_ERROR);
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 自动填充参数
        this.fillSpaceBySpaceLevel(space);
        // 校验数据
        this.validSpace(space, false);
        // 2. 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = this.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        // 3. 更新
        boolean res = this.updateById(space);
        ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
        return true;
    }

    @Override
    public Boolean editSpace(SpaceEditRequest spaceEditRequest) {
        // 1. 校验
        ThrowUtils.throwIf(spaceEditRequest.getId() <= 0, ErrorCodeEnum.PARAMS_ERROR);
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 校验数据
        this.validSpace(space, false);
        // 2. 判断是否存在
        long id = spaceEditRequest.getId();
        Space oldSpace = this.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCodeEnum.NOT_FOUND_ERROR);
        // 3. 更新
        boolean res = this.updateById(space);
        ThrowUtils.throwIf(!res, ErrorCodeEnum.OPERATION_ERROR);
        return true;
    }

    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        // 仅本人或者管理员可编辑
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH_ERROR);
        }
    }
}




